<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>新增操作员用户</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="${ctx}/rs/js/jquery.validate.min.js"></script>
<script src="${ctx}/rs/js/jquery.form.js" type="text/javascript"></script>

</head>
<body>
<form id="form1" class="form-horizontal" action="${ctx}/user/save.htm" method="post" enctype="multipart/form-data">
      <div class="form-group">
        <label for="name" class="col-sm-2 control-label item ">登录账户：</label>
        <div class="col-sm-6  ">
          <input type="text" class="form-control " id="userId" name="userId"/>
        </div>
        <span class="help-block col-sm-4" id="valierr" style="color:#FF9966">*</span>
      </div>
      
      <div class="form-group">
        <label for="name" class="col-sm-2 control-label item ">密码：</label>
        <div class="col-sm-6  ">
          <input type="password" class="form-control " id="pwd" name="pwd" />
        </div>
        <span class="help-block col-sm-4" id="valierr" style="color:#FF9966">*</span>
      </div>
      
      <div class="form-group">
        <label for="name" class="col-sm-2 control-label item ">昵称：</label>
        <div class="col-sm-6  ">
          <input type="text" class="form-control " id="nickName" name="nickName" />
        </div>
        <span class="help-block col-sm-4" id="valierr" style="color:#FF9966">*</span>
      </div>

	  <div class="form-group">
        <label for="name" class="col-sm-2 control-label item ">角色：</label>
        <div class="col-sm-6  wid300">
          <c:forEach items="${roles}" var="role">
              <label class="checkbox-inline">
                <input type="checkbox" name="roleIds" value="${role.id}"/>${role.name}
              </label>
          </c:forEach>
		  <div id="errorMsg" style="display: none;color: red">暂无角色</div>
        </div>
      </div>
      
      <div class="form-group">
        <label for="name" class="col-sm-2 control-label item ">头像：</label>
        <div class="col-sm-6  ">
          <span id="preview" class="preview">
           <img id="imghead" src="" alt="" class="damFront"/>
         </span> 
          <input type="file" id="iconFile" name="iconFile" class="upload" accept="image/*" onchange="previewImage(this)"/>
          <p class="help-block col_red">支持格式jpg或png，尺寸350*350，文件大小不能超过80kb</p>
        </div>
      </div>
	  
      <div class="form-group">
        <div class="col-sm-10 text-center pt15">
		  <shiro:hasPermission name="user:save">
		     <button type="button" class="btn btn-primary btn-lg srt-btn active mr30" onclick="valiSubmit()">提交</button>
		     <button type="reset" class="btn btn-default btn-lg srt-btn active">重置</button>
          </shiro:hasPermission>
        </div>
      </div>

      <div class="form-group">
        <div class=" col-sm-10">
          <span id="error-text" style="color: #FF0000;"></span>
        </div>
      </div>
</form>	

<script type="text/javascript" src="${ctx}/rs/js/bootstrapQ.min.js"></script>
<script src="${ctx}/rs/js/messages_zh.min.js"></script>
<script type="text/javascript">

    //自定义验证
    $.validator.addMethod("alnum", function(value, element) {
        return this.optional(element) || /^[a-zA-Z0-9]+$/.test(value);
    }, "只能包括英文字母和数字");
	$.validator.addMethod("limitPwd", function(value, element) {
        return this.optional(element) || /^\S*$/.test(value);
    }, "不允许空格");
	$.validator.addMethod("limitType", function(value, element) {
		var str = value.substr(value.lastIndexOf(".")).toLowerCase();
		return this.optional(element) || /.(png|jpg)$/.test(str);
	}, "上传文件格式不正确!");
	$.validator.addMethod("nickNameLimit", function(value, element) {
	    return this.optional(element) || /^[a-zA-Z0-9\u4e00-\u9fa5_]+$/.test(value);
	}, "只能包括中文、字母、数字、下划线");
	jQuery.validator.addMethod("eq", function(value, element, param) {
		if(value==$(param).val()){
			return false;
		}else{
			return true;
		}
		}, $.validator.format("昵称不能和登录账户重复！"));
	
	//图片尺寸验证规则
	$.validator.addMethod("limitPicSize", function(value, element) {
		var width=$('#imghead').attr("width");
		var heights=$('#imghead').attr("height");
		if(width==350 && heights==350){
			return true;
		}
	}, "上传图片尺寸不符，请上传尺寸为350*350");
	
	//图片大小验证规则
	$.validator.addMethod("limitImgSize", function(value, element) {
		var browserCfg = {};
		var ua = window.navigator.userAgent;
		if (ua.indexOf("MSIE")>=1){
			browserCfg.ie = true;
		}else if(ua.indexOf("Firefox")>=1){
			browserCfg.firefox = true;
		}else if(ua.indexOf("Chrome")>=1){
			browserCfg.chrome = true;
		}
		var filesize = 0;
		if(browserCfg.firefox || browserCfg.chrome ){
			filesize = element.files[0].size;
		}else if(browserCfg.ie){
			var obj_img = document.getElementById('imghead');
			obj_img.dynsrc=element.value;
			filesize = obj_img.fileSize;
		}else{
			return false;
		}
		if(filesize == -1){
			return false;
		}else if(filesize / 1024 > 80){
			//以上大小根据实际情况更改
			return false;
		}else{
			return true;
		}
	}, "上传图片大小不能超过80KB!");
	
	//初始化验证 start
	var form = $('#form1');
	form.validate({
		rules : {
			userId : {
				maxlength : 11,
				required : true,
				alnum : "alnum",
				remote : {
					type : "GET",
					url : "${ctx}/user/isUserExist.htm",
					data : {
						userId :function(){return $("#userId").val();}
					}
				}
			},
			pwd : {
				rangelength : [6,20], 
				required : true,
				limitPwd : "limitPwd"
			},
			nickName : {
				maxlength : 15,
				required : true,
				nickNameLimit : "nickNameLimit",
				eq:"#userId"
			},
			iconFile : {
				limitType : "limitType",
				limitPicSize:"limitPicSize",
				limitImgSize:"limitImgSize"
			}, 
		},
		messages : {
			  pwd : {
				  rangelength : "请输入6~20个字符"
			  },
			  userId : {
				  remote : "登录账号已存在！"
			  }
		},
		highlight : function(element) {
			$(element).closest('.form-group').removeClass('success').addClass(
					'error');
		},
		success : function(element) {
			element.text('OK!').addClass('valid').closest('.form-group')
					.removeClass('error').addClass('success');
		}
	});
	/** end */

	$(function() {
		var roles = "${roles}";
		if (roles && roles.length) {
			$("#errorMsg").hide();
		} else {
			$("#errorMsg").show();
		}
	});
	
	//图片上传预览    IE是用了滤镜。
	function previewImage(file){
	  var MAXWIDTH  = 350; 
	  var MAXHEIGHT = 350;
	  var div = document.getElementById('preview');
	  if (file.files && file.files[0]){
	      div.innerHTML ='<img id=imghead>';
	      var img = document.getElementById('imghead');
	      img.onload = function(){
	        var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
	        img.width  =  img.offsetWidth;
	        img.height =   img.offsetHeight;
//	         img.style.marginLeft = rect.left+'px';
	        img.style.marginTop = rect.top+'px';
	      }
	      var reader = new FileReader();
	      reader.onload = function(evt){img.src = evt.target.result;}
	      reader.readAsDataURL(file.files[0]);
	  }
	  else //兼容IE
	  {
	    var sFilter='filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="';
	    file.select();
	    var src = document.selection.createRange().text;
	    div.innerHTML = '<img id=imghead>';
	    var img = document.getElementById('imghead');
	    img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src;
	    var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
	    status =('rect:'+rect.top+','+rect.left+','+rect.width+','+rect.height);
	    div.innerHTML = "<div id=divhead style='width:"+rect.width+"px;height:"+rect.height+"px;margin-top:"+rect.top+"px;"+sFilter+src+"\"'></div>";
	  }
	}
	
	function clacImgZoomParam( maxWidth, maxHeight, width, height ){
	    var param = {top:0, left:0, width:width, height:height};
	    if( width>maxWidth || height>maxHeight )
	    {
	        rateWidth = maxWidth;
	        rateHeight = maxHeight;
	        
	        if( rateWidth > rateHeight )
	        {
	            param.width =  maxWidth;
	            param.height = rateHeight;
	        }else
	        {
	            param.width = maxWidth;
	            param.height = maxHeight;
	        }
	    }
	    param.left = Math.round((maxWidth - param.width) / 2);
	    param.top = Math.round((maxHeight - param.height) / 2);
	    return param;
	}

	function valiSubmit() {
		if (form.valid()) {
			var options = {
					dataType : "json",
					beforeSubmit : function() {
						$(".unable").show();
					},
					success : function(result) {
						if(!$('.unable').is(':hidden')){
							$(".unable").hide();
						}
						if (result) {
							// 普通消息提示条
							bootstrapQ.msg({
								msg : '保存成功！',
								type : 'success',
								time : 2000
							});
							//触发隐藏确认的按钮，引用回调方法关闭窗口并刷新列表
							$("button.bsok").click();
						} else {
							bootstrapQ.msg({
								msg : '保存失败！',
								type : 'danger',
								time : 2000
							});
						}
					},
					error : function(result) {
						if(!$('.unable').is(':hidden')){
							$(".unable").hide();
						}
						bootstrapQ.msg({
							msg : '保存失败！',
							type : 'danger',
							time : 2000
						});
					}
				};
				form.ajaxSubmit(options);
				return false;
		}
	}
	
</script>
</body>
</html>